"use strict"

// Constants
var SHORTHAND={F:'Fairway', S:'Short', L:'Left', R:'Right', G:'Green', O:'Over', B:'Bunker', P:'Penalty', X:'Lost Ball', D:'Duff', T:'Trouble'}
var LOOKUP={'-1':'Birdy', '0':'Par', '1':'Bogey'}

// Globals
var gamehtml, holecount, summary
var totalscore, totalyds, totalpar, totalhcap, totalnet, totalputs, totaldrive, totalss
var ninescore, nineyds, ninepar, ninehcap,  ninenet, nineputs, ninedrive, niness

function resetall(){
    //
    //
    //
    reset9()
    gamehtml   = ''
    holecount  = 0
    totalscore = 0
    totalyds   = 0
    totalpar   = 0
    totalhcap  = 0
    totalnet   = 0
    totalputs  = 0
    totaldrive = 0
    totalss    = 0
    summary    = {}
}

function reset9(){
    //
    //
    //
    ninescore = 0
    nineyds   = 0
    ninepar   = 0
    ninehcap  = 0
    ninenet   = 0
    nineputs  = 0
    ninedrive = 0
    niness    = 0
}

function count(what){
    //
    // Count and colour things for a summary table.
    // Return whatever you are given.
    //
    if (what in summary){
        summary[what] += 1
    }
    else{
        summary[what] = 1
    }
    if (what=='Fairway')
        return what.fontcolor('green')
    if (what=='Penalty' || what=='Lost Ball' || what=='Duff')
        return what.fontcolor('red')
    if (what=='Green')
        return what.fontcolor('lightgreen').sub()
    if (what=='Bunker')
        return what.fontcolor('brown')
    return what
}

function teecolour(g){
    //
    // default = yellow -> goldenrod
    // white -> blue
    // rest: red
    //
    var tee = g.getAttribute('tee') || 'yellow'
    if (tee=='white')
        return 'blue'
    if (tee=='yellow')
        return 'goldenrod'
    return 'red'
}

function gamestart(g){
    //
    //
    //
    var verbose = !g.getAttribute('publish')
    var tee = teecolour(g)
    var player = g.getAttribute('player') || 'Who'
    var course = g.getAttribute('course') || 'Where'
    var date = g.getAttribute('date') || 'When'
    gamehtml += '<h1>'+player+'@ '+course+' ('+date+')</h1>'
    gamehtml += '<table border="1">'
    gamehtml += '<thead><tr>'
    gamehtml += '<th>Hole</th>'
    if(verbose)gamehtml += '<th style="color:black;background:'+tee+'">Yds</th>'
    gamehtml += '<th style="color:black;background:'+tee+'">Par</th>'
    if(verbose)gamehtml += '<th style="color:black;background:'+tee+'">SI</th>'
    if(verbose)gamehtml += '<th>Shorthand</th>'
    if(0)gamehtml += '<th>Drive</th>'
    gamehtml += '<th>Summary</th>'
    gamehtml += '<th>Score</th>'
    if(0)gamehtml += '<th>Puts</th>'
    if(0)gamehtml += '<th>Total</th>'
    gamehtml += '<th>HCap</th>'
    gamehtml += '<th>Nett</th>'
    gamehtml += '<th>SS</th>'
    gamehtml += '</tr></thead>'
    gamehtml += '<tbody>'
}

function stylescore(score){
    //
    //
    //
    score=score.toString()
    if (score.indexOf('Par')>0)
        return ' style="background:green"'
    if (score.indexOf('Bogey')>0)
        return ' style="background:blue"'
    if (score.indexOf('Birdy')>0)
        return ' style="background:red"'
    if (score.indexOf('-')>0)
        return ' style="background:orange;color:black"'
    if (score.indexOf('Hole')>0)
        return ' style="background:deeppink"'
    return ''
}

function gamerow(g, hole, yds, par, si, shorthand, drive, summary, score, puts, total, hcap, net, ss){
    //
    //
    //
    var verbose = !g.getAttribute('publish')
    var tee = teecolour(g)
    gamehtml += '<tr>'
    gamehtml += '<td>'+hole+'</td>'
    if(verbose)gamehtml += '<td style="color:black;background:'+tee+'">'+(yds||'')+'</td>'
    gamehtml += '<td style="color:black;background:'+tee+'">'+par+'</td>'
    if(verbose)gamehtml += '<td style="color:black;background:'+tee+';text-align:right">'+si+'</td>'
    if(verbose)gamehtml += '<td>'+shorthand+'</td>'
    if(0)gamehtml += '<td>'+(drive||'')+'</td>'
    gamehtml += '<td style="text-align:right">'+summary+'</td>'
    gamehtml += '<td'+stylescore(score)+'>'+(score||'')+'</td>'
    if(0)gamehtml += '<td>'+(puts||'')+'</td>'
    if(0)gamehtml += '<td>'+total+'</td>'
    gamehtml += '<td>'+(hcap||'')+'</td>'
    gamehtml += '<td'+stylescore(net)+'>'+(net||'')+'</td>'
    gamehtml += '<td>'+(ss||'')+'</td>'
    gamehtml += '</tr>'
}

function namescore(score, delta){
    //
    //
    //
    if (score==1)
        return 'Hole in 1'
    var description = LOOKUP[delta.toString()]
    if (description)
        return description
    if (delta<0)
        return delta.toString()
    return '+'+delta.toString()
}

function joinscore(score, description){
    //
    //
    //
    return score+description.sub()
}

function gamehole(g, h){
    //
    //
    //
    holecount += 1

    var shorthand = h.textContent.toUpperCase()

    var yds = parseInt(h.getAttribute('yds')) || ''
    if (yds) {
        nineyds  += yds
        totalyds += yds
    }

    var par = parseInt(h.getAttribute("par"))
    ninepar  += par
    totalpar += par

    var si = h.getAttribute('si') || ''

    var hcap = parseInt(h.getAttribute('hcap')) || 0
    ninehcap  += hcap
    totalhcap += hcap

    var result  = ''
    var score   = 0
    var puts    = 0
    var drive   = ''
    var collect = ''

    for ( var i = 0; i < shorthand.length; i++ ){
        var ch = shorthand[i]
        if (!drive){
            if (ch>='0' && ch<='9'){
                collect += ch
                continue
            }
            else if (collect){
                drive = collect
                var _drive= parseInt(collect)
                totaldrive += _drive
                ninedrive  += _drive
            }
            else{
                drive = ' '
            }
            if (ch=='F'){
                count('FIR')
            }
        }
        if (SHORTHAND[ch]){
            result += count(SHORTHAND[ch])+', '
            score += 1
        }
        else if ('H'==ch){
            result += count('In The Hole!').fontcolor('pink')
            score += 1
        }
        else if ('M'==ch){
            result += (count('Mulligan').fontcolor('gray') +', ')
        }
        else if ('1'<=ch && '9'>=ch){
            result += (count(ch+' Put')+'.').sub().fontcolor('lightblue')
            puts = parseInt(ch)
            score     += puts
            totalputs += puts
            nineputs  += puts
        }
        else{
            count(ch)
            score += 1
            result+= ch+', ' // unknown character
        }
        if ((ch=='G') && score<(par-1))
            count('GIR')
        if ((ch=='G') && (score-hcap)<(par-1))
            count('GIR(Nett)')
    }

    totalscore += score
    ninescore  += score

    var net = score-hcap
    totalnet += net
    ninenet  += net

    var ss = par+hcap-score+2
    if (ss<0)ss=0
    totalss += ss
    niness  += ss

    var description    = count(namescore (score, score-par))
    var netdescription = namescore(net, net-par)

    gamerow( g, holecount, yds, par, si, shorthand.small(), drive, result, joinscore(score, description), puts, totalscore, hcap, joinscore(net, netdescription), ss )
    if (holecount==9){
        gamerow(g, 'OUT', nineyds, ninepar, '', '', ninedrive, '', ninescore, nineputs, '', ninehcap, ninenet, niness)
        reset9()

    }
}

function gamesummary(){
    //
    //
    //
    gamehtml += '<h2>Summary</h2>'
    gamehtml += '<table border="1">'
    gamehtml += '<caption></caption>'
    gamehtml += '<thead><tr>'
    gamehtml += '<th>What</th>'
    gamehtml += '<th>Count</th>'
    gamehtml += '</tr></thead>'
    gamehtml += '<tbody>'
    var keys=Object.keys(summary)
    keys.sort()
    for (var i=0; i<keys.length; i++) {
        gamehtml += '<tr><td>'+keys[i].small()+'</td><td>'+summary[keys[i]].toString().small()+'</td></tr>'
    }
    gamehtml += '</tbody></table>'

}

function gameend(g){
    //
    //
    //
    gamerow(g, 'IN', nineyds, ninepar, '', '', ninedrive, '', ninescore, nineputs, '', ninehcap, ninenet, niness)
    gamerow(g, 'TOTAL', totalyds, totalpar, '', '', totaldrive, '', totalscore, totalputs, '', totalhcap, totalnet, totalss)
    gamehtml += '</tbody></table>'
    gamesummary()
    g.insertAdjacentHTML('beforebegin', gamehtml)
    resetall()

}

// Main...
resetall()
var games=document.getElementsByTagName('golf')
for (var g=0; games.length; g++){
    var game = games[0]
    gamestart(game)
    for (var h=0; h<game.childNodes.length; h++){
        var hole = game.childNodes[h]
        if (hole.nodeName.substr(0,3)=='PAR'){
            hole.setAttribute('par', hole.nodeName.substr(3))
            gamehole(game, hole)
        }
    }
    gameend(game)
    game.parentNode.removeChild(game)
}
